package data;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.sql.Date;
import java.sql.Time;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Iterator;
import java.util.Set;

/**
 * @author doyl
 *
 */
public class StockDataFetch {

	synchronized public static String getstockData(String address) throws IOException{
		URL url = new URL(address);
		BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(),"GBK"));
		String s = new String();
		if((s=reader.readLine())!=null){
			return s;
		}
		return null;
	}
	
	public static TimeStock getTimeStock(String code){
		TimeStock ts = new TimeStock();
		String string = StockURLDataBuffer.getUrlData(code);
		if(string==null){
			return null;
		}
		String[] s = string.split(",");
		if(s.length<32){
			return null;
		}
		ts.setCode(code);
		ts.setStockName(s[0]);
		ts.setBeginPrice(new BigDecimal(s[1]));
		ts.setPreDayPrice(new BigDecimal(s[2]));
		ts.setCurPrice(new BigDecimal(s[3]));
		ts.setMaxPrice(new BigDecimal(s[4]));
		ts.setMinPrice(new BigDecimal(s[5]));
		ts.setCurBuyPrice(new BigDecimal(s[6]));
		ts.setCurSalePrice(new BigDecimal(s[7]));
		try{
			ts.setQty((int)(Integer.parseInt(s[8])));
		}catch(NumberFormatException e){
			ts.setQty(0);
		}
		ts.setAmount(new BigDecimal(s[9]));
		ts.setFirstBuyqty(Integer.parseInt(s[10]));
		ts.setFirstBuyPrice(new BigDecimal(s[11]));
		ts.setSecondBuyqty(Integer.parseInt(s[12]));
		ts.setSecondBuyPrice(new BigDecimal(s[13]));
		ts.setThirdBuyqty(Integer.parseInt(s[14]));
		ts.setThirdBuyPrice(new BigDecimal(s[15]));
		ts.setForthBuyqty(Integer.parseInt(s[16]));
		ts.setForthBuyPrice(new BigDecimal(s[17]));
		ts.setFifthBuyqty(Integer.parseInt(s[18]));
		ts.setFifthBuyPrice(new BigDecimal(s[19]));
		ts.setFirstSaleqty(Integer.parseInt(s[20]));
		ts.setFirstSalePrice(new BigDecimal(s[21]));
		ts.setSecondSaleqty(Integer.parseInt(s[22]));
		ts.setSecondSalePrice(new BigDecimal(s[23]));
		ts.setThirdSaleqty(Integer.parseInt(s[24]));
		ts.setThirdSalePrice(new BigDecimal(s[25]));
		ts.setForthSaleqty(Integer.parseInt(s[26]));
		ts.setForthSalePrice(new BigDecimal(s[27]));
		ts.setFifthSaleqty(Integer.parseInt(s[28]));
		ts.setFifthSalePrice(new BigDecimal(s[29]));
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		try {
			ts.setDate(new Date(sdf.parse(s[30]).getTime()));
		} catch (ParseException e) {
			e.printStackTrace();
		}
		String[] time = s[31].split(":");
		Time t = new Time(Integer.parseInt(time[0]), Integer.parseInt(time[1]), Integer.parseInt(time[2]));
		ts.setTime(t);

		return ts;
	}

	public static void refreshData(Set<String> codeSet) {
		
		/**
		 * 优化网络
		 */
		StringBuffer codeSh = new StringBuffer("sz399001");
		String stockStr = StockURLDataBuffer.getUrlData("sz399001");
		fetch(codeSh);
		String stockStr2 = StockURLDataBuffer.getUrlData("sz399001");
		if(stockStr2.equals(stockStr)){
			return;
		}
		
		int size = Constant.BatchCount;
		int i =0;
		StringBuffer codeBatch = new StringBuffer();
		for (Iterator<String> iterator = codeSet.iterator(); iterator.hasNext();i++) {
			String code = iterator.next();
			codeBatch = codeBatch.append(code);
			if(i<size){
				codeBatch.append(",");
			}else{
				fetch(codeBatch);
				i=0;
			}
		}
		if(!"".equals(codeBatch.toString().trim())){
			fetch(codeBatch);
		}
	}
	
	private static void fetch(StringBuffer codeBatch) {
		String codeUrl = "http://hq.sinajs.cn/list="+codeBatch.toString();
		URL url;
		try {
			url = new URL(codeUrl);
			
			HttpURLConnection urlCon = (HttpURLConnection)url.openConnection();
			
			urlCon.setConnectTimeout(3000);
			urlCon.setReadTimeout(3000);

			BufferedReader reader = null;
			reader = new BufferedReader(new InputStreamReader(urlCon.getInputStream(),"GBK"));
			String codeData;
			while((codeData = reader.readLine())!=null){
				codeData = codeData.replaceAll("var hq_str_", "");
				codeData = codeData.replaceAll("\"", "");
				String[] codeString = codeData.split("=");
				if("".equals(codeString[1].trim())||codeString[1]==null||codeString[1].length()<10){
					continue;
				}
				StockURLDataBuffer.put(codeString[0], codeString[1]);
			}
			codeBatch.setLength(0);
		} catch (MalformedURLException e1) {
			e1.printStackTrace();
		} catch (SocketTimeoutException e) {
			System.out.println("time out:"+codeUrl);
			fetch(codeBatch);
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
}
